import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/internal/Subscription';

import { MonitorVo, PageVo } from 'src/app/shared/models';
import { MonitorService } from 'src/app/core/service/monitor.service';

@Component({
    selector: 'monitor-list',
    templateUrl: './monitor-list.component.html',
    styleUrls: ['./monitor-list.component.scss']
})
export class MonitorListComponent implements OnInit, OnDestroy {
    private monitorListSubscription: Subscription;
    newMonitorList: PageVo<MonitorVo> = { pageIndex: 1, pageSize: 10, total: 0, data: null };
    historyMonitorList: PageVo<MonitorVo> = { pageIndex: 1, pageSize: 10, total: 0, data: null };
    isActive = false;
    tabIndex = 0;

    constructor(
        private monitorService: MonitorService,
        private activeRoute: ActivatedRoute
    ) {
        this.activeRoute.queryParams.subscribe(queryData => {
            if (queryData.warningListActive === 'true') {
                this.isActive = true;
            }
            if (queryData.warningListTab === 'history') {
                this.tabIndex = 1;
                this.getHistoryList();
            }
        });

        this.monitorListSubscription = this.monitorService.monitorList$.subscribe(
            (monitorList: Array<MonitorVo>) => {
                if (monitorList.length > 0) {
                    this.newMonitorList.data = monitorList;
                    this.newMonitorList.total = monitorList.length;
                    this.isActive = true;
                }
            }
        );
    }

    ngOnInit(): void { }

    public emptyData() {
        return this.newMonitorList.data == null || this.newMonitorList.data.length === 0;
    }

    public getHistoryList() {
        if (!this.historyMonitorList.data) {
            this.monitorService.getHistoryMonitorList().subscribe(
                (monitorPage) => {
                    this.historyMonitorList = monitorPage;
                }
            );
        }
    }

    public updateNewMonitorList(pageVo: PageVo<any>) {
        const pageIndex = pageVo.pageIndex;
        const pageSize = pageVo.pageSize;

    }

    public updateHistoryMonitorList(pageVo: PageVo<any>) {
        const pageIndex = pageVo.pageIndex;
        const pageSize = pageVo.pageSize;
        console.log(pageVo, pageIndex, pageSize);
        this.monitorService.getHistoryMonitorList(pageIndex, pageSize).subscribe(
            (monitorPage) => {
                this.historyMonitorList = monitorPage;
            }
        );
    }

    ngOnDestroy(): void {
        this.monitorListSubscription.unsubscribe();
    }
}
